package com.guaju.yueshangLife.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.guaju.yueshangLife.R;
import com.guaju.yueshangLife.base.BaseActivity;
import com.guaju.yueshangLife.bean.CodeLoginEvent;
import com.guaju.yueshangLife.constant.ConstanceValue;
import com.guaju.yueshangLife.event.CodeEvent;
import com.guaju.yueshangLife.global.BaseApplication;
import com.guaju.yueshangLife.net.ApiEntity;
import com.guaju.yueshangLife.net.NetworkUtil;
import com.guaju.yueshangLife.utils.DoubleClickUtil;
import com.guaju.yueshangLife.utils.PreferenceUtil;
import com.guaju.yueshangLife.utils.ProgressUtil;
import com.guaju.yueshangLife.utils.ToastUtil;
import com.guaju.yueshangLife.utils.Utils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class CodeLoginActivity extends BaseActivity {


    @BindView(R.id.phone_edit)
    EditText phone_edit;
    @BindView(R.id.phone_edit_clear)
    FrameLayout phone_edit_clear;
    @BindView(R.id.code_clear)
    FrameLayout code_clear;
    @BindView(R.id.code_edit)
    EditText code_edit;
    @BindView(R.id.send_authcode)
    TextView send_authcode;
    @BindView(R.id.bt_login)
    Button bt_login;
    @BindView(R.id.user_protocol_tv)
    TextView user_protocol_tv;
    @BindView(R.id.tv_go_count_login)
    TextView tvGoCountLogin;
    @BindView(R.id.tv_go_regist)
    TextView tvGoRegist;

    public static final String FROM_TYPE = "from_type";
    public static final String FROM_GUIDE = "from_guide";
    boolean isFromGuide = false;
    boolean isLoginBtClicked = false;
    @BindView(R.id.fl_back)
    FrameLayout flBack;
    @BindView(R.id.tv1)
    TextView tv1;


    private int from_type = 0;
    private int to_type = 0;
    String tabId = "";
    private int fromInt;
    private String verify_key;
    private Intent intent;

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_code_login);
    }

    @Override
    protected void bindViews() {
        ButterKnife.bind(this);
        phone_edit_clear.setVisibility(View.INVISIBLE);
        code_clear.setVisibility(View.INVISIBLE);
        bt_login.setClickable(false);
        setBtnStatus();
    }

    @Override
    protected void processLogic(Bundle savedInstanceState) {
        EventBus.getDefault().register(this);

    }

    @OnClick({R.id.bt_login, R.id.phone_edit_clear, R.id.code_clear,
            R.id.send_authcode, R.id.user_protocol_tv})
    public void OnClick(View v) {
        switch (v.getId()) {
            case R.id.bt_login:
                //防止连击
                if (DoubleClickUtil.isDoubleClick(1000)) {
                    return;
                }
                if (!isLoginBtClicked) {
                    loginHM();
                    isLoginBtClicked = true;
                }
                break;
            case R.id.phone_edit_clear:
                phone_edit.setText("");
                phone_edit_clear.setVisibility(View.INVISIBLE);
                bt_login.setEnabled(false);
                break;
            case R.id.ib_authcode_clear:
                code_edit.setText("");
                code_clear.setVisibility(View.INVISIBLE);
                break;
            case R.id.send_authcode:
                sendCode();
                break;
            case R.id.user_protocol_tv:
                Bundle bundle = new Bundle();
                bundle.putString(ConstanceValue.H5_TITLE_NAME, "用户协议");
                bundle.putString(ConstanceValue.WEB_URL, "https://university-img.cyhm.com/static/default/agreement.html");
                Intent intent = new Intent(CodeLoginActivity.this, H5WebviewActivity.class);
                startActivity(intent, bundle);
                break;
        }

    }

    @Override
    protected void setListener() {
        phone_edit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s.toString())) {
                    phone_edit_clear.setVisibility(View.INVISIBLE);
                } else {
                    if (phone_edit.isFocusable()) {
                        phone_edit_clear.setVisibility(View.VISIBLE);
                        code_clear.setVisibility(View.INVISIBLE);
                    }
                }
                setBtnStatus();
            }

            @Override
            public void afterTextChanged(Editable s) {
                String str = s.toString();
                if (str.contains("\n")) {
                    str = str.replaceAll("\n", "");
                    phone_edit.setText(str);
                }
            }
        });
        phone_edit.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (!phone_edit.getText().toString().equals("")) {
                    phone_edit_clear.setVisibility(View.VISIBLE);
                }
                code_clear.setVisibility(View.INVISIBLE);
                return false;
            }
        });

        code_edit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s.toString())) {
                    code_clear.setVisibility(View.INVISIBLE);
                } else {
                    if (code_edit.isFocusable()) {
                        code_clear.setVisibility(View.VISIBLE);
                        phone_edit_clear.setVisibility(View.INVISIBLE);
                    }
                }
                setBtnStatus();
            }

            @Override
            public void afterTextChanged(Editable s) {
                String str = s.toString();
                if (str.contains("\n")) {
                    str = str.replaceAll("\n", "");
                    code_edit.setText(str);
                }
            }
        });
        code_edit.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (!code_edit.getText().toString().equals("")) {
                    code_clear.setVisibility(View.VISIBLE);
                }
                phone_edit_clear.setVisibility(View.INVISIBLE);
                return false;
            }
        });

    }

    private void loginHM() {
        if (Utils.isMobileNO(phone_edit.getText().toString())) {
            if (!TextUtils.isEmpty(code_edit.getText().toString()) && Utils.isSmsCodeNO(code_edit.getText().toString()) && Utils.isMobileNO(phone_edit.getText().toString())) {
                ProgressUtil.showProgressDialog(CodeLoginActivity.this, "请稍等...");
                ProgressUtil.setUnCancelable();
                //TODO 点击按钮登录的逻辑
                ApiEntity.codeLogin(verify_key, code_edit.getText().toString());

            }
        } else {
//            ToastUtils.showCustomToast("请正确输入", ToastUtils.EXCEPTION_WARNING, ToastUtils.showCenter);
            ToastUtil.show("请正确输入");
        }
    }


    private void sendCode() {
        if (!NetworkUtil.isConnected(BaseApplication.getInstance())) {
            Toast.makeText(this, "网络连接异常", Toast.LENGTH_SHORT).show();
            return;
        }
        String mobile = phone_edit.getText().toString();
        if (Utils.isMobileNO(mobile)) {
            // 调用 发送验证码接口
            ApiEntity.getLoginCode(mobile);
        } else {
            ToastUtil.show("请输入正确手机号");
        }
    }

    private void setBtnStatus() {
        if (Utils.isMobileNO(phone_edit.getText().toString()) && !TextUtils.isEmpty(code_edit.getText().toString()) && Utils.isSmsCodeNO(code_edit.getText().toString()) && Utils.isMobileNO(phone_edit.getText().toString())) {
            bt_login.setTextColor(getResources().getColor(R.color.white));
            bt_login.setBackgroundResource(R.drawable.shape_login_enable_bg);
            bt_login.setEnabled(true);
        } else {
            bt_login.setTextColor(getResources().getColor(R.color.white));
            bt_login.setBackgroundResource(R.drawable.shape_login_unable_bg);
            bt_login.setEnabled(false);
        }
    }

    private CountDownTimer timer = new CountDownTimer(60000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            send_authcode.setText((millisUntilFinished / 1000) + "秒重发");
            send_authcode.setTextColor(getResources().getColor(R.color.c_gray2));
            send_authcode.setEnabled(false);
        }

        @Override
        public void onFinish() {
            send_authcode.setEnabled(true);
            send_authcode.setTextColor(Color.parseColor("#FF6C00"));
            send_authcode.setText("重新获取");
        }
    };

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(CodeEvent event) {
        timer.start();
        String phone = event.getPhone();
        verify_key = event.getVerify_key();
        bt_login.setClickable(true);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(CodeLoginEvent event) {
        timer.start();
        int code = event.getCode();
        String msg = event.getMsg();
        String token_type = event.getToken_type();
        String access_token = event.getAccess_token();

        if (500 == code) {
            ProgressUtil.dismissProgressDialog();
            Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
        } else if (200 == code) {
            Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
            ProgressUtil.dismissProgressDialog();
            PreferenceUtil.setTokenType(token_type);
            PreferenceUtil.setToken(access_token);
            PreferenceUtil.setIsLogin(true);
            String trim = phone_edit.getText().toString().trim();
            PreferenceUtil.setFphone(trim);
            finish();
        } else if (412 == code) {
            Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
            ProgressUtil.dismissProgressDialog();
            PreferenceUtil.setTokenType(token_type);
            PreferenceUtil.setToken(access_token);
            String trim = phone_edit.getText().toString().trim();
            PreferenceUtil.setFphone(trim);
            PreferenceUtil.setIsLogin(true);
            startActivity(new Intent(CodeLoginActivity.this, SetupPasswordActivity.class));
            finish();
        } else {
            Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
        }
        bt_login.setClickable(true);
        //TODO 真正登录逻辑
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.tv_go_count_login, R.id.tv_go_regist})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_go_count_login:
                finish();
                break;
            case R.id.tv_go_regist:
                intent = new Intent(CodeLoginActivity.this, RegistActivity.class);
                startActivity(intent);
                finish();
                break;
        }
    }


    @OnClick(R.id.fl_back)
    public void onViewClicked() {
        finish();
    }
}